package com.mocaris.android.gank.adapter

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.RecyclerView

open abstract class BaseRecyclerAdapter<T>(val context: Context) :
    RecyclerView.Adapter<BaseRecyclerAdapter.ViewHolder>() {

    var onItemClickListener: OnItemClickListener? = null

    private val data = arrayListOf<T>()

    fun refreshData(list: List<T>) {
        if (this.data.isNotEmpty()) {
            this.data.clear()
        }
        this.data.addAll(list)
        notifyDataSetChanged()
    }

    fun appendData(list: List<T>) {
        val size = this.data.size
        this.data.addAll(list)
        notifyItemRangeChanged(size, this.data.size)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        holder.itemView.setOnClickListener {
            onItemClickListener?.onItemClick(holder, position)
        }
        super.onBindViewHolder(holder, position, payloads)
    }

    fun getItem(position: Int): T {
        return data[position]
    }

    override fun getItemCount(): Int {
        return data.size
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    interface OnItemClickListener {
        fun onItemClick(
            viewHolder: ViewHolder,
            position: Int
        )
    }

}